import * as fse from 'fs-extra';
import JSON5 from 'json5';
import path from 'path';

import { runHvigorAsync } from '../../common/common';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,

    // 当前都是5.0 api已经不用管
    apiVersion: APIVersion.API11,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility,
  },
  modulesOption: [ModuleTemplateType.StaticLibrary],
};

// 闭源har 配置了 useTsHar=true 时，产物文件为 ts后缀，并且module.json5 中 main 字段 也是同步修改的
const testfun: TestCaseFun = async (project, taskConfig, record) => {
  // 1. 创建API12 stage 工程 ，添加 StaticLibrary 模块， 获取模块路径
  const staticLibraryPath = project.getModule('staticLibrary').moduleRootPath();

  // 2、先构建一次 后续增量处理
  let commands: string[] = 'assembleHar -p buildMode=release'.split(' ');
  let result = await runHvigorAsync(project.projectRootPath(), commands);
  record.addStep('初始构建har', result);
  expect(result.stdout).toContain('BUILD SUCCESSFUL');

  // 3、 修改 module.json  添加 UseTsHar 字段
  const harModuleJson5Path = path.resolve(staticLibraryPath, 'src', 'main', 'module.json5');
  let moduleJson5Data = await fse.readFile(harModuleJson5Path);
  let moduleJson5 = JSON5.parse(moduleJson5Data.toString());
  moduleJson5['module']['metadata'] = [
    {
      name: 'UseTsHar',
      value: 'true',
    },
  ];
  await fse.writeFile(harModuleJson5Path, JSON5.stringify(moduleJson5, null, 2), 'utf-8');

  // 4. 执行同步编译构建 进行增量构建成功
  commands = 'assembleHar -p buildMode=release'.split(' ');
  result = await runHvigorAsync(project.projectRootPath(), commands);
  record.addStep('添加UseTsHar后增量构建', result);
  expect(result.stdout).toContain('BUILD SUCCESSFUL');

  // 5、判断 产物是ts， 并且 判断 oh-package.json5 中的main 字段 也是 ts 结尾的
  // build\default\cache\default\default@PackageHar 里面有index.ts文件存在
  let indexFilePath = path.resolve(staticLibraryPath, 'build', 'default', 'cache', 'default', 'default@PackageHar', 'Index.ts');
  let tsFile: boolean = fse.existsSync(indexFilePath);

  // 需要注意sdk版本，增量问题是sdk  修复的， 5.0.3.401SP3 ide 带的sdk 即可。修改变量记得重启ide
  expect(tsFile).toEqual(true);

  // 6、并且oh-package.json5 中的main 字段 也是 index.ts 后缀
  let packageJsonFilePath = path.resolve(staticLibraryPath, 'build', 'default', 'cache', 'default', 'default@PackageHar', 'oh-package.json5');
  let packageJsonFile: boolean = fse.existsSync(packageJsonFilePath);
  expect(packageJsonFile).toEqual(true);

  let ohPackageJson5Data = await fse.readFile(packageJsonFilePath);
  let ohPackageJson5 = JSON5.parse(ohPackageJson5Data.toString());
  let main = ohPackageJson5['main'];
  expect(main).toEqual('Index.ts');

  // 7、修改 UseTsHar 为 false
  moduleJson5Data = await fse.readFile(harModuleJson5Path);
  moduleJson5 = JSON5.parse(moduleJson5Data.toString());
  moduleJson5['module']['metadata'] = [
    {
      name: 'UseTsHar',
      value: 'false',
    },
  ];
  await fse.writeFile(harModuleJson5Path, JSON5.stringify(moduleJson5, null, 2), 'utf-8');

  // 8、进行增量 构建， 产物中 改为js
  commands = 'assembleHar -p buildMode=release'.split(' ');
  result = await runHvigorAsync(project.projectRootPath(), commands);
  record.addStep('修改UseTHar 为 false 后增量构建', result);
  expect(result.stdout).toContain('BUILD SUCCESSFUL');

  // 9、判断 产物是ts， 并且 判断 oh-package.json5 中的main 字段 也是 ts 结尾的
  // build\default\cache\default\default@PackageHar 里面有Index.ts文件存在
  indexFilePath = path.resolve(staticLibraryPath, 'build', 'default', 'cache', 'default', 'default@PackageHar', 'Index.js');
  tsFile = fse.existsSync(indexFilePath);
  expect(tsFile).toEqual(true);

  packageJsonFilePath = path.resolve(staticLibraryPath, 'build', 'default', 'cache', 'default', 'default@PackageHar', 'oh-package.json5');
  packageJsonFile = fse.existsSync(packageJsonFilePath);
  expect(packageJsonFile).toEqual(true);

  ohPackageJson5Data = await fse.readFile(packageJsonFilePath);
  ohPackageJson5 = JSON5.parse(ohPackageJson5Data.toString());
  main = ohPackageJson5['main'];
  expect(main).toEqual('Index.js');
};

TestCaseBuilder.builder()
  .caseName('DTS2024060318767')
  .description('适配UseTsHar字段，打闭源har包时，判断产物和增量问题')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.DTS).build())
  .testFun(testfun)
  .load();
